package com.lovo;

import java.util.Arrays;
import java.util.Scanner;

public class Game {
    public static void main(String[] args) {
        //声明两个数组存放正确答案和用户答案
        int[] arr = new int[4];
        int[] input = new int[4];
        //得到正确答案
        setArr(arr);

        System.out.println(Arrays.toString(arr));

        for (int i = 5; i > 0; i--) {
            System.out.println("你还有" + i + "次机会");
            //得到用户答案
            getInput(input);
            //比较答案
            String ret = cmpArr(arr, input);
            System.out.println(ret);
            if ("4A0B".equals(ret)) {
                break;
            }

        }

    }

    //生成随机数
    public static void setArr(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) (Math.random() * 10);
            for (int j = 0; j < i; j++) {
                if (arr[i] == arr[j]) {
                    i--;
                    break;
                }
            }
        }
    }

    //获得输入的数
    public static void getInput(int[] arr) {
        while (true) {
            Scanner scan = new Scanner(System.in);
            try {
                System.out.println("请输入一个四位数");
                int num = scan.nextInt();
                toArray(arr, num);
                if (isRepeat(arr)) {
                    System.out.println("数字有重复");
                } else {
                    break;
                }
            } catch (Exception e) {
                System.out.println("只能输入数字");
            }
        }

    }

    //判断数组是否有重复项
    public static boolean isRepeat(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] == arr[j]) {
                    return true;
                }
            }
        }
        return false;
    }

    //四位数转数组
    public static void toArray(int[] arr, int num) {
        for (int i = 3; i >= 0; i--) {
            arr[i] = num % 10;
            num /= 10;
        }
    }

    //数组比较
    public static String cmpArr(int[] arr, int[] input) {
        int a = 0, b = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length; j++) {
                if (arr[i] == input[j]) {
                    if (i == j) {
                        a++;
                    } else {
                        b++;
                    }
                }
            }
        }

        return a + "A" + b + "B";
    }
}
